<template>
  <div class="settings">
    <div class="settings_btn">
      <Button class="btn"
              style="margin-right:24px;"
              @click="disShop">门店列表</Button>
      <div class="hbtn">
        <Button class="btn"
                type="primary"
                @click="unplodaImg">上传物料</Button>
        <div class="tips">
          <p>支持格式：.jpg、.png</p>
          <p>规格：180*120；大小：≤100KB</p>
          <p>文件名称格式为: K802_Pxxxx.png或者K802_Pxxxx.jpg</p>
        </div>
      </div>
    </div>
    <div class="listImg"
         v-if="dataArr.length&&isShow">
      <div class="listImg-item">
        <ul>
          <li v-for="(item,index) in dataArr"
              :key="index">
            <img class="dsImg"
                 :src="item.materialUrl">
            <div class="set-icon">
              <div class="set-icon-st">
                <i class="iconsys iconsetting"
                   @click="allSet(item,index)"
                   title="设置">
                </i>
              </div>
              <div class="set-icon-de">
                <!-- <Poptip confirm
                        title="你确定要删除吗？"
                        @on-ok="delet(item)"
                        @on-cancel="canceld"> -->
                <i class="iconsys icondel" v-if="item.materialName.split('.')[0] !== 'K802_P0000'"
                   @click="delet(item)"
                   title="删除">
                </i>
                <!-- </Poptip> -->
              </div>
            </div>
            <p class="time">{{item.materialName}}</p>
            <p class="time">{{item.updateTime}}</p>
          </li>
        </ul>
      </div>
    </div>
    <div class="nodata"
         v-if="!dataArr.length&&isShow">
      <img :src="src">
    </div>
    <div v-if="dataArr.length&&isShow">
      <div class="content_page">
        <Page :total="total"
              ref="pages"
              :current="data.offset"
              @on-change="selectPage"
              :page-size="data.limit"
              @on-page-size-change="selectSize"
              class-name="page"
              show-sizer
              show-total />
      </div>
    </div>
    <Modal title="确认提示"
           width='400'
           @on-visible-change="closed"
           v-model="modalShow2">
      <Row type='flex'
           justify="space-between"
           align='middle'
           style="margin-bottom:20px;">
        <Col style="padding-left:10px;">
        <Icon type="ios-alert"
              size="30"
              color="#ffbf00" />
        <span style="margin-left:10px;font-weight:bold;color:#666666;">是否确认删除</span>
        <Poptip word-wrap trigger="hover"
                  width="240"
                  content="删除后,将解绑与门店的关系,在没有新的待机动画更新时,则展示出厂设置">
            <Icon type="ios-alert-outline"
                  size="18"
                  style='margin-left:5px' />
          </Poptip>
        </Col>
      </Row>
      <Form :model="delValidate"
            ref="delValidate"
            :label-width="50"
            :rules="rulesdelValidate">
        <FormItem label="原因:"
                  prop="remark">
          <Input v-model="delValidate.remark"
                 style="width:280px;"
                 :maxlength="100"
                 type="textarea"
                 :autosize="{minRows: 2,maxRows: 5}"
                 placeholder="输入删除原因" />
          <p style="text-align:right;width:280px">已输入{{delValidate.remark?delValidate.remark.length:0}}/100</p>
        </FormItem>
      </Form>
      <div slot="footer"
           class="foot">
        <Button class="btn"
                @click="resitDelValidate">取消</Button>
        <Button class="btn"
                style="margin-right:16px;"
                type="primary"
                @click="delresit">确认</Button>
      </div>
    </Modal>
    <select-shop :checkdList="checkdList"
                 :dataTree="dataTree"
                 :modalShow="modalShow"
                 @oncancel="selctshopCancle"
                 @selctshop="volumeSet"
                 v-if="modalShow">
    </select-shop>
    <Drawer v-model="modal2"
            title="上传物料"
            :mask-closable="true"
            class="shopDrawer"
            width="540">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            class="shopDrawer_form">
        <FormItem label="上传物料:"
                  prop="materialUrl"
                  class="set_ct_form_up">
          <Upload ref="upload"
                  :format="['jpg','png']"
                  :max-size="100"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :data='uploadParmas'
                  :on-success="handleSuccess"
                  type="drag"
                  :show-upload-list="false"
                  :action="$config.uploadImg"
                  style="display: inline-block;width:96px;">
            <img :src="formValidate.materialUrl?formValidate.materialUrl:defaultUrl1"
                 style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                 alt="">
            <p v-if="formValidate.materialUrl"
               class="replace_tit">更换</p>
          </Upload>
          <div style="width:165px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;display: inline-block;vertical-align:top;">
            <p>支持格式：jpg、png</p>
            <p>规格：180*120</p>
            <p>大小：≤100K</p>
            <p>文件名称格式为: K802_Pxxxx,其中xxxx的范围为0001-9999</p>
          </div>
        </FormItem>
        <FormItem class="shopDrawer_form_btn">
          <Button @click="handleReset"
                  style="width:72px">取消</Button>
          <Button type="primary"
                  @click="handleSubmit"
                  :disabled='isDisabled'
                  style="width:72px;margin-left:20px">确认</Button>
        </FormItem>
      </Form>
    </Drawer>
    <Drawer v-model="modal1"
            title="门店列表"
            :mask-closable="true"
            class="shopDrawer02"
            width="540">
      <div class="cont">
        <div class="cont-serch">
          <span style="margin-right:16px;">门店名称:</span>
          <!-- <Input search
                 v-model="data2.shopName"
                 style="width:180px;"
                 @on-keyup="filterSpace"
                 :maxlength="100"
                 @on-search="searchShop"
                 placeholder="请选择" /> -->
          <Select v-model="data2.shopName"
                  filterable
                  style="width:180px;"
                  :clearable='true'
                  @on-change='changeStore'>
            <Option v-for="item in storeList"
                    :value="item.shopName"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select>
        </div>
        <div class="tablist">
          <ul>
            <li v-for="(item,index) in dataArr2"
                :key="index">
              <div class="tablist-item">
                <div class="tablist-item-name">{{item.shopName}}</div>
                <div class="tablist-item-name">{{item.updateTime}}</div>
                <div class="
                     tablist-item-img"><img :src="item.materialUrl?item.materialUrl:defaultUrl"></div>
              </div>
            </li>
            <Spin size="large"
                  v-if="spinShow"></Spin>
          </ul>

        </div>
      </div>
      <div>
        <div class="content_page"
             style="text-align: right;
    padding: 20px 0;">
          <Page :total="total2"
                ref="pagesd"
                :current="data2.offset"
                @on-change="selectPage2"
                :page-size="data2.limit"
                @on-page-size-change="selectSize2"
                class-name="page"
                show-sizer
                show-total />
        </div>
      </div>
    </Drawer>
  </div>
</template>
<script>
import SelectShop from '@/view/components/select-shop/select-shop.vue'
import { getOrgAllTree } from '@/api/system/org'
import { getShopList } from '@/api/system/store'
import error from '@/assets/images/error-page/error.svg'
import { getMaterialInfos, getWholeMaterialInfos, shopMaterialList, saveWholeMaterialInfos, deleteWholeMaterialInfos, saveMaterialInfos } from '@/api/setting'
export default {
  components: { SelectShop },
  data () {
    return {
      loadStatus: false,
      title: '刷卡器待机图片设置',
      modal1: false,
      dataArr: [],
      dataArr2: [],
      src: error,
      spinShow: true,
      isShow: false,
      materialId: '',
      isDisabled: false,
      isDelete: true,
      shopData: {
        merchantId: this.$store.state.user.merchantId,
        offset: 0,
        limit: 99999,
        status: 1,
        shopNameLike: ''
      },
      storeList: [], // 门店列表
      total: 10,
      total2: 10,
      isSerch: true,
      uploadParmas: {
        project: 'material',
        type: 'animation'
      },
      data: {
        offset: 1,
        limit: 10,
        merchantId: this.$store.state.user.merchantId,
        materialType: 1,
        shopId: this.$route.query.id
        // materialId: ""
      },
      data2: {
        offset: 1,
        limit: 10,
        merchantId: this.$store.state.user.merchantId,
        materialType: 1,
        shopId: this.$route.query.id,
        shopName: ''
      },
      delValidate: {
        remark: '',
        materialId: ''
      },
      model: true,
      modal2: false,
      checkAll: false,
      modalShow: false,
      modalShow2: false,
      defaultUrl: require('@/assets/images/player.jpg'),
      defaultUrl1: require('@/assets/images/default.png'),
      formValidate: {
        materialUrl: '',
        materialName: ''
      },
      checkdList: [], // 已选的数组
      isChangecheckdList: [],
      name: '',
      shopIdList: [],
      dataTree: [],
      rulesdelValidate: {
        remark: [{ required: true, type: 'string', message: '删除理由不能为空', trigger: 'blur' }]
      },
      ruleValidate: {
        materialUrl: [{
          required: true, message: '上传的物料不能为空'
        }]
      },
      listStyle: {
        width: '230px',
        height: '286px'
      }
    }
  },
  watch: {
    modalShow (val) {
      if (!val) {
        this.dataTree = []
        this.checkdList = []
      }
    },
    modal2 (val) {
      if (!val) {
        this.$refs.formValidate.resetFields()
        // this.loadStatus = true
      }
    }
  },
  mounted () {
    this.getList({ offset: 0 })
    this.chooseShopList()
    if (!this.hasPermission('moms:globalsetting:idlescreen')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    filterSpace () {
      this.data2.shopName = this.data2.shopName.replace(/\s+/g, '')
    },
    selctshopCancle () {
      this.modalShow = false
    },
    changeTitle (arr) {
      arr.forEach(item => {
        this.$set(item, 'title', item.orgName)
        this.$set(item, 'checked', false)
        if (item.hasOwnProperty('childList') && item.childList.length > 0) {
          this.changeTitle(item.childList)
        }
      })
    },
    disShop () {
      this.modal1 = true
      this.getList2({ offset: 0 })
    },
    // 获取门店树
    allSet (row, index) {
      this.materialId = row.materialId
      // 获取已选门店列表
      getOrgAllTree({ 'merchantId': this.$store.state.user.merchantId, orgType: 1 }).then(res => {
        if (res.data.status === 200) {
          this.dataTree = [res.data.data]
          this.changeTitle(this.dataTree)
          shopMaterialList({
            'merchantId': this.$store.state.user.merchantId,
            'materialType': 1,
            'materialId': row.materialId,
            'offset': 0,
            'limit': 999
          }).then(res => {
            this.modalShow = true
            if (res.data.status === 200) {
              this.checkdList = res.data.data
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 关闭弹框
    closed (val) {
      this.$refs.delValidate.resetFields()
    },
    // 获取门店列表
    chooseShopList () {
      getShopList({ 'merchantId': this.$store.state.user.merchantId, offset: '0', limit: '5000' }).then(res => {
        if (res.data.status === 200) {
          this.storeList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch((err) => {
        this.$Message.error(`${err}`)
      })
    },
    changeStore () {
      this.getList2({ offset: 0 })
    },
    // 获取列表
    getList (res) {
      getMaterialInfos({ ...this.data, offset: (this.data.offset - 1) * this.data.limit, ...res }).then(res => {
        if (res.data.status === 200) {
          this.isShow = true
          this.dataArr = res.data.data
          this.total = res.data.totalCount
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
      // this.loadStatus = false
    },
    handleFormatError (file) {
      // this.loadStatus = false
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    getList2 (res) {
      this.spinShow = true
      getWholeMaterialInfos({ ...this.data2, offset: (this.data2.offset - 1) * this.data2.limit, ...res }).then(res => {
        if (res.data.status === 200) {
          this.spinShow = false
          this.dataArr2 = res.data.data
          this.total2 = res.data.totalCount
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    selectPage (page) {
      this.getList({ offset: (page - 1) * this.data.limit })
    },
    selectSize (num) {
      this.data.limit = num
      this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.data.limit })
    },
    selectPage2 (page) {
      this.getList2({ offset: (page - 1) * this.data2.limit })
    },
    selectSize2 (num) {
      this.data2.limit = num
      this.getList2({ offset: (this.$refs.pagesd.currentPage - 1) * this.data2.limit })
    },
    searchShop () {
      this.getList2({ offset: 0 })
    },
    // 取消
    handleReset () {
      this.modal2 = false
      this.$refs.formValidate.resetFields()
    },
    // 删除
    delet (obj) {
      this.modalShow2 = true
      this.delValidate.materialId = obj.materialId
    },
    // 取消
    canceld () {

    },
    handleSubmit () {
      // 保存物料
      this.$refs.formValidate.validate((val) => {
        if (val) {
          if (this.isDisabled) {
            return
          }
          this.isDisabled = true
          setTimeout(() => {
            saveWholeMaterialInfos({
              merchantId: this.$store.state.user.merchantId,
              materialType: 1,
              materialUrl: this.formValidate.materialUrl,
              materialName: this.formValidate.materialName,
              creatorId: this.$store.state.user.userId,
              creatorName: this.$store.state.user.userName
            }).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.$Message.success('保存成功')
                this.modal2 = false
                this.$refs.formValidate.resetFields()
                this.getList({ offset: 0 })
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }, 200)
        }
      })
    },
    // 获取图片尺寸
    getcicun (url, name) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width !== 180 && img.height !== 120) {
          _this.formValidate.materialUrl = ''
          _this.$Notice.warning({
            title: '上传的图片规格不符',
            duration: 1.5
          })
        } else {
          if (name.indexOf('_') !== -1) {
            if (name.split('_')[0] === 'K802' && name.split('_')[1].split('.')[0].length === 5 && name.split('_')[1].substring(0, 1) === 'P' && (/^[0-9]+$/.test(name.split('_')[1].substring(1, 4)))) {
              // this.$Message.success('上传成功！')
              _this.formValidate.materialUrl = url
              _this.formValidate.materialName = name
            } else {
              _this.$Notice.warning({
                title: '图片名称格式不正确,K802_Pyyyy',
                duration: 1.5
              })
            }
          } else {
            _this.$Notice.warning({
              title: '图片名称格式不正确,K802_Pyyyy',
              duration: 1.5
            })
          }
        }
      }
    },
    // 上传物料
    unplodaImg () {
      this.modal2 = true
    },
    // 查看详情
    openDraw () {
      this.historyShow = true
    },
    volumeSet (val) {
      if (val.length > 0) {
        this.shopIdList = []
        val.forEach(ele => {
          this.shopIdList.push(ele.id)
        })
        saveMaterialInfos({
          materialType: 1,
          merchantId: this.$store.state.user.merchantId,
          creatorId: this.$store.state.user.userId,
          creatorName: this.$store.state.user.userName,
          shopIdList: this.shopIdList,
          materialId: this.materialId,
          batchFlag: 0
        }).then(res => {
          if (res.data.status === 200) {
            this.getList({ offset: 0 })
            this.modalShow = false
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.modalShow = false
        this.$Message.error('请至少选择一个门店操作')
      }
    },
    cancel () { },
    del (row, index) { },
    change (index) { },
    // 设置
    set () {
      this.model = true
    },
    handleSuccess (response, file) {
      this.$refs.formValidate.resetFields()
      let url = response.full_img_url
      let name = file.name
      if (url) {
        this.getcicun(url, name)
      }
      // }
    },
    resit () {
      this.model = false
    },
    resitDelValidate () {
      this.modalShow2 = false
      this.$refs.delValidate.resetFields()
    },
    delresit () {
      this.$refs.delValidate.validate((val) => {
        if (val) {
          if (this.isDelete) {
            if (!this.isDelete) {
              return
            }
            this.isDelete = false
            if (this.$refs.pages.currentPage !== 1) {
              if (this.total % this.data.limit === 1) {
                this.$refs.pages.currentPage = this.$refs.pages.currentPage - 1
              }
            }
            setTimeout(() => {
              deleteWholeMaterialInfos(this.delValidate).then(res => {
                this.isDelete = true
                if (res.data.status === 200) {
                  this.$Message.success('删除成功')
                  this.getList({ offset: (this.$refs.pages.currentPage - 1) * this.data.limit })
                  this.modalShow2 = false
                  this.$refs.delValidate.resetFields()
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            }, 200)
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.ivu-upload {
  width: 96px;
  height: 96px;
  position: relative;
  .replace_tit {
    position: absolute;
    bottom: 0;
    width: 96px;
    opacity: 0.6;
    background: #2d8cf0;
    height: 24px;
    text-align: center;
    line-height: 24px;
    font-size: 12px;
    color: #ffffff;
    display: none;
  }
}
.ivu-upload:hover .replace_tit {
  display: block;
}
.settings {
  .nodata {
    text-align: center;
  }
  .content_page {
    height: 80px;
    line-height: 80px;
    display: flex;
    padding-right: 20px;
    flex-direction: row;
    justify-content: flex-end;
  }
  .settings_btn {
    height: 80px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 24px;
    .btn {
      width: 80px;
    }
    .hbtn {
      width: 80px;
      height: 32px;
      position: relative;
    }

    .tips {
      padding: 6px 14px;
      background: #585e6b;
      border-radius: 3px;
      position: absolute;
      display: none;
      right: 0;
      top: 38px;
      > p {
        font-size: 12px;
        color: #ffffff;
        width: 167px;
        line-height: 18px;
      }
    }
    .tips:before {
      content: "";
      position: absolute;
      right: 36px;
      top: -12px;
      width: 0;
      height: 0;
      border-top: 6px solid transparent;
      border-left: 6px solid transparent;
      border-right: 6px solid transparent;
      border-bottom: 6px solid #585e6b;
    }
    .hbtn:hover .tips {
      display: block;
    }
  }
  .listImg {
    padding-top: 12px;
    .listImg-item {
      width: 1044px;
      min-width: 1044px;
      margin: auto;
      > ul {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        li {
          width: 180px;
          list-style: none;
          height: 189px;
          // background-color: red;
          margin-left: 36px;
          margin-bottom: 40px;
          .dsImg {
            width: 100%;
            height: 120px;
            vertical-align: top;
          }
          .set-icon {
            height: 40px;
            padding: 8px 0;
            background: #f8f8f9;
            display: flex;
            align-items: center;
            > div {
              width: 50%;
              text-align: center;
            }
            .set-icon-st {
              border-right: 1px solid #e8eaec;
            }
          }
          .time {
            text-align: center;
            font-size: 12px;
            color: #808695;
            line-height: 17px;
            margin-top: 12px;
          }
        }
        > li:nth-of-type(5n) {
          margin-right: 0;
        }
      }
    }
  }
  // 对话框
}
</style>
<style lang="less">
.foo_tips {
  position: absolute;
  right: 49px;
  top: 32px;
  display: inline-block;
  font-size: 12px;
  line-height: 14px;
  color: #c5c8ce;
}
</style>

<style>
.settings .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
  left: 14px;
}
.foot .btn {
  width: 72px;
}
.shopDrawer_form_btn {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding-top: 16px;
  padding-right: 20px;
  border-top: 1px solid #e8eaec;
  text-align: right;
}
.shopDrawer02 .cont .cont-serch {
  height: 56px;
  background: #f8f8f9;
  border-bottom: 1px solid #e8eaec;
  display: flex;
  align-items: center;
  padding-left: 24px;
  font-size: 12px;
  color: #464c5b;
}
.shopDrawer02 .ivu-drawer-header {
  padding: 14px 24px;
}
.shopDrawer02 .ivu-drawer-body {
  padding: 0;
}
.shopDrawer02 .tablist ul li {
  padding: 0px 24px;
  list-style: none;
}
.shopDrawer02 .tablist ul li .tablist-item {
  padding: 16px 0;
  border-bottom: 1px solid #e8eaec;
  display: flex;
  align-items: center;
}
.shopDrawer02 .tablist ul li .tablist-item .tablist-item-name {
  flex: 1;
}
.shopDrawer02 .tablist ul li .tablist-item .tablist-item-img {
  width: 90px;
  height: 60px;
}
.shopDrawer02 .tablist ul li .tablist-item .tablist-item-img img {
  vertical-align: top;
  width: 90px;
  height: 60px;
}
</style>
